package com.hp.tiger.chapter7;

import com.google.common.base.Stopwatch;

import java.util.concurrent.TimeUnit;

/**
 * @author XavierDong
 **/
public class ImmutablePerformance {

    public static void main(String[] args) throws InterruptedException {


//        ImmutableObj  8994
//        SyncObj 9921
        Stopwatch started = Stopwatch.createStarted();
        //2512
        SyncObj syncObj = new SyncObj();
        syncObj.setName("Alex");

//        ImmutableObj syncObj = new ImmutableObj("Alex");


        Thread t1 = new Thread() {
            @Override
            public void run() {
                for (long i = 0L; i < 1000000L; i++) {
                    System.out.println(Thread.currentThread().getName() + " " + syncObj.toString());
                }
            }
        };
        t1.start();

        Thread t2 = new Thread() {
            @Override
            public void run() {
                for (long i = 0L; i < 1000000L; i++) {
                    System.out.println(Thread.currentThread().getName() + " " + syncObj.toString());
                }
            }
        };

        t2.start();
        t1.join();
        t2.join();

        System.out.println("Elapsed time " + started.stop().elapsed(TimeUnit.MILLISECONDS));

    }


}

final class ImmutableObj {
    private final String name;

    public ImmutableObj(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "ImmutableObj{" +
                "name='" + name + '\'' +
                '}';
    }
}

final class SyncObj {

    private String name;

    public synchronized void setName(String name) {
        this.name = name;
    }

    @Override
    public synchronized String toString() {
        return "SyncObj{" +
                "name='" + name + '\'' +
                '}';
    }
}